package com.ellricky.baselib.ui.student

import android.os.Build
import android.view.View
import android.widget.AdapterView
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.andr.common.widget.refresh.RvRefreshListener
import com.ellricky.baselib.BaseConstant
import com.ellricky.baselib.R
import com.ellricky.baselib.adapter.PhotoAdapter
import com.ellricky.baselib.cache.LocalCacheUtil
import com.ellricky.baselib.entity.*
import com.ellricky.baselib.entity.new.LifePhoto
import com.ellricky.baselib.http.HttpUtils
import com.ellricky.baselib.ui.base.BaseTakePhotoActivity
import com.ellricky.baselib.util.*
import com.ellricky.baselib.util.photo.TakePhotoUtil
import com.lxj.xpopup.XPopup
import kotlinx.android.synthetic.main.activity_student_photo.*
import kotlinx.android.synthetic.main.activity_student_photo.rvView
import kotlinx.android.synthetic.main.base_layout_rv.*
import okhttp3.Call
import org.devio.takephoto.model.TResult


class StudentPhotoActivity : BaseTakePhotoActivity(), RvRefreshListener,
    AdapterView.OnItemClickListener {

    private val photoAdapter by lazy {
        PhotoAdapter(this)
    }

    private var refresh: Boolean = true
    private var paramMap: MutableMap<String, String>? = mutableMapOf()
    private var dataSource: MutableList<LifePhoto> = mutableListOf()

    private val memberId: String by lazy {
        intent.getStringExtra(BaseConstant.KEY_ID)
    }

    override fun getContentLayout(): Int {
        return R.layout.activity_student_photo
    }

    override fun initUIView() {
        super.initUIView()
        setRightBtn(0)
        mTvTitle.text = "生活照"
        rvView.init(this)
        loadDataOnInit()
    }

    override fun onClickBtnRight() {
        // 添加图片
        EDialogUtil.showTakePhotoDialog(this) { dialogInterface,
                                                item ->
            dialogInterface.dismiss()
            createImageUri()
            TakePhotoUtil.configTakePhotoOption(takePhoto)
            TakePhotoUtil.configCompress(takePhoto)

            if (item == 0) {
                // 拍照
                TakePhotoUtil.takeCamera(takePhoto, null, imageUri)
            } else if (item == 1) {
                TakePhotoUtil.takePicOne(takePhoto, null, imageUri)
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun takeSuccess(result: TResult?) {
        val path = FileUtil.fileToBase64(result?.image?.originalPath ?: "")
        val url = EAppUtil.getApiHost()

        val params = hashMapOf<String, String>(
            "action" to "teacherAddMemberImg",
            "member_id" to memberId,
            "eid" to LocalCacheUtil.getUid(),
            "img" to path
        )

        HttpUtils.getInstance().postFrom(url, params,
            object : NewECallback<Any>(this) {
                override fun onSuccess(data: Any?, msg: String?) {
                    loadDataOnInit()
                }
            })
    }

    override fun setAdapter(rv: RecyclerView) {
        photoAdapter.setOnItemClickListener(this)
        rv.adapter = photoAdapter
        rv.layoutManager = GridLayoutManager(this, 2)
    }

    private fun loadDataOnInit() {
        rvView.loadContent(true)
    }

    override fun loadData(p0: Boolean) {
        this.refresh = p0
        val url = EAppUtil.getApiHost()
        initParamMap()
        paramMap?.apply {
            put("action", "teacherMemberImgList")
            put("eid", LocalCacheUtil.getUid())
            put("member_id", memberId)
            put("page_size", "40")
        }

        HttpUtils.getInstance().postFrom(url, paramMap,
            object : NewEListCallback<LifePhoto>(this) {
                override fun onSuccess(data: MutableList<LifePhoto>, msg: String?) {
                    this@StudentPhotoActivity.dataSource = data
                    rvView.onLoadFinish(data, refresh)
                }

                override fun onErrorCode(code: String?, msg: String?) {
                    super.onErrorCode(code, msg)
                    rvView.onLoadFinish(dataSource, refresh)
                }

                override fun onError(call: Call?, e: Exception?, id: Int) {
                    super.onError(call, e, id)
                    rvView.onLoadFinish(dataSource, refresh)
                }
            })
    }

    private fun initParamMap() {
        paramMap?.put("page", rvView.curPage.toString())
    }

    override fun updateAdapterData(refresh: Boolean) {
        if (refresh) photoAdapter.refresh(dataSource) else photoAdapter.loadMore(dataSource)
    }

    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        val imageUrl = photoAdapter[position].img_adr
        XPopup.Builder(this)
            .asImageViewer(null, imageUrl, GlideImageLoader())
            .show()
    }
}